<template>
  <a-modal title-align="start" title="代交货" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="900">
    <div style="color: red">注意：由于该供应商还未注册到顾本ERP系统，所以无法操作供应链协同，需要交货的单子就由采购部代替其提交。 </div>
    <div class="mt10 flex">
      <div class="img-con">
        <a-scrollbar style="width: 100%; height: 600px; overflow: auto">
          <a-image-preview-group infinite>
            <a-image class="mb10" v-for="(item, index) in props.getPicList(props.info)" :key="index" :src="item.url" width="200" />
          </a-image-preview-group>
        </a-scrollbar>
      </div>
      <div class="basic-info">
        <div class="info-con flex">
          <div class="label">产品SKU：</div>
          <div>{{ $extract(props.info, 'product.productSku') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">定制编号：</div>
          <div>{{ $extract(props.info, 'customCode') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">定制类型：</div>
          <div>{{ $extract(props.info, 'customInfo.customType') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">刻字内容：</div>
          <div>{{ $extract(props.info, 'customInfo.fontTxt') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">字体：</div>
          <div>{{ $extract(props.info, 'customInfo.fontFamily') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">材质：</div>
          <div>{{ $extract(props.info, 'customInfo.material') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">戒指尺码：</div>
          <div>{{ $extract(props.info, 'customInfo.ringSize') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">电镀颜色：</div>
          <div>{{ $extract(props.info, 'customInfo.platinColor') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">石头：</div>
          <div>{{ $extract(props.info, 'customInfo.stone') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">链条：</div>
          <!-- <div>{{ props.getfittingName(props.info) }}</div> -->
          <textLimit position="top" :rows="1" :val="getfittingName(props.info)"></textLimit>
        </div>
        <div class="info-con flex">
          <div class="label">字印：</div>
          <div>{{ $extract(props.info, 'customInfo.fontPrint') }}</div>
        </div>
        <div class="info-con flex">
          <div class="label">备注：</div>
          <div>{{ $extract(props.info, 'customInfo.remark') }}</div>
        </div>
      </div>
      <div class="setting">
        <a-descriptions :data="deliveryInfo" :label-style="{ textAlign: 'right' }" :column="1" bordered>
          <template #label="{ label, data }">
            <div v-if="!data.tip">{{ label }}：</div>
            <a-popover :content="data.tip" v-else>
              <p>
                <icon-question-circle />
                <span>{{ label }}</span>
              </p>
            </a-popover>
          </template>

          <template #value="{ label, data }">
            <div v-if="data.label == '半成品毛坯供应方'">{{ getSupplierName(info) }}</div>
            <div v-if="data.label == '数量'">{{ props.info.qtyPurchase }}</div>
            <div v-if="data.label == '材质单价(元/g)'">{{ $extract(props.info, 'supplierCloseCost.amtAvgMaterial') }}</div>
            <div v-if="data.label == '单件加工费'">{{ $extract(props.info, 'supplierCloseCost.amtAvgProcess') }}</div>
            <div v-if="data.label == '材质净重(g)'">
              <a-input v-model="materialNetWeight" @input="getAmount" placeholder="请输入" :disabled="getSupplierName(info) == '需求方'" />
            </div>
            <div v-if="data.label == '损耗率(%)'">
              <a-input v-model="attritionRate" @input="getAmount" placeholder="请输入" :disabled="getSupplierName(info) == '需求方'" />
            </div>
            <div v-if="data.label == '连耗重量(g)'">{{ continuousWeight }}</div>
            <div v-if="data.label == '材质金额'">{{ materialAmount }}</div>
            <div v-if="data.label == '加工费'">{{ formatFloatToFourDecimalPlaces(props.info.supplierCloseCost.amtAvgProcess ? props.info.supplierCloseCost.amtAvgProcess : 0 * props.info.qtyPurchase ? props.info.qtyPurchase : 0) }}</div>
            <div v-if="data.label == '石头费用'">
              <a-input v-model="stoneAmount" @input="getAmount" placeholder="请输入" />
            </div>
            <div v-if="data.label == '链条费用'">
              <a-input v-model="chainAmount" @input="getAmount" placeholder="请输入" />
            </div>
            <div v-if="data.label == '其他费用'">
              <a-input v-model="otherAmount" @input="getAmount" placeholder="请输入" />
            </div>
            <div v-if="data.label == '合计金额'">{{ allAmount }}</div>
            <div v-if="data.label == '税率(%)'">{{ props.info.supplierCloseCost.taxRate }}{{ props.info.supplierCloseCost.includeTax ? '（含税）' : '（不含税）' }}</div>
            <div v-if="data.label == '税金'">{{ taxAmount }}</div>
          </template>
        </a-descriptions>
      </div>
    </div>
    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { number } from 'echarts'
  import { onMounted, ref, computed } from 'vue'
  import { batchSupplierSubmitVerify } from '@/api/purchase'
  import { Message } from '@arco-design/web-vue'
  let props = defineProps(['modelValue', 'type', 'getPicList', 'info', 'getfittingName'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  let materialNetWeight = ref<any>('')
  let attritionRate = ref<any>('')
  let continuousWeight = ref<any>(0)
  let materialAmount = ref<any>(0)
  let stoneAmount = ref<any>()
  let chainAmount = ref<any>()
  let otherAmount = ref<any>()
  let allAmount = ref<any>(0)
  let taxAmount = ref<any>(0)
  let submitLoading = ref(false)
  let deliveryInfo = ref([
    { label: '半成品毛坯供应方', tip: '' },
    { label: '数量', tip: '' },
    { label: '材质单价(元/g)', tip: '' },
    { label: '单件加工费', tip: '' },
    { label: '材质净重(g)', tip: '材质净重是指产品出库时扣除石头和链条之外的重量。' },
    { label: '损耗率(%)', tip: '生产加工过程中主材质的损耗率' },
    { label: '连耗重量(g)', tip: '连耗重量，是指净重加上损耗的重量。连耗重量=材质净重+（材质净重*损耗率）' },
    { label: '材质金额', tip: '材质金额=材质单价*连耗重量' },
    { label: '加工费', tip: '加工费=单件加工费*数量' },
    { label: '石头费用', tip: '如果石头是由供应商提供的，则供应商在交货的时候可以填上石头费用' },
    { label: '链条费用', tip: '如果链条是由供应商提供的，则供应商在交货的时候可以填上链条费用' },
    { label: '其他费用', tip: '本次定制单产生的其他费用' },
    { label: '合计金额', tip: '合计金额=材质金额+加工费+石头费用+链条费用+其他费用' },
    { label: '税率(%)', tip: '' },
    { label: '税金', tip: '税金=合计费用*税率' },
  ])

  function formatFloatToFourDecimalPlaces(num: string | number) {
    // 将数字转换为字符串
    let numStr = num.toString()

    // 检查是否包含小数点
    if (numStr.includes('.')) {
      // 如果包含小数点，则使用 toFixed 保留四位小数
      return parseFloat(num.toFixed(4)).toString()
    } else {
      // 如果不包含小数点（即整数），则直接返回原字符串
      return numStr
    }
  }

  const getAmount = () => {
    let w = 0
    if (materialNetWeight.value && attritionRate.value) {
      w = Number(materialNetWeight.value) + Number(materialNetWeight.value * (attritionRate.value / 100))
      continuousWeight.value = formatFloatToFourDecimalPlaces(w)
    } else {
      continuousWeight.value = formatFloatToFourDecimalPlaces(w)
    }
    materialAmount.value = formatFloatToFourDecimalPlaces(continuousWeight.value * props.info.supplierCloseCost.amtAvgMaterial)

    let num1 = materialAmount.value ? parseFloat(materialAmount.value) : 0
    let num2 = formatFloatToFourDecimalPlaces(props.info.supplierCloseCost.amtAvgProcess * props.info.qtyPurchase) ? parseFloat(formatFloatToFourDecimalPlaces(props.info.supplierCloseCost.amtAvgProcess * props.info.qtyPurchase)) : 0
    let num3 = stoneAmount.value ? parseFloat(stoneAmount.value) : 0
    let num4 = chainAmount.value ? parseFloat(chainAmount.value) : 0
    let num5 = otherAmount.value ? parseFloat(otherAmount.value) : 0

    allAmount.value = formatFloatToFourDecimalPlaces(num1 + num2 + num3 + num4 + num5)

    taxAmount.value = formatFloatToFourDecimalPlaces((allAmount.value * props.info.supplierCloseCost.taxRate) / 100)
  }

  const submit = async () => {
    let params = {
      list: [
        {
          ...props.info,
          id: props.info.id,
          supplierCloseCost: {
            ...props.info?.supplierCloseCost,
            amtChain: chainAmount.value,
            amtMaterial: materialAmount.value,
            amtOther: otherAmount.value,
            amtProcess: props.info.supplierCloseCost.amtAvgProcess,
            amtStone: stoneAmount.value,
            amtTax: taxAmount.value,
            amtTotal: allAmount.value,
            attritionRate: attritionRate.value,
            wgtAttrition: formatFloatToFourDecimalPlaces(Number(materialNetWeight.value * (attritionRate.value / 100))),
            wgtContinueAttrition: continuousWeight.value,
            wgtNetMaterial: materialNetWeight.value,
          },
        },
      ],
    }

    try {
      submitLoading.value = true
      const res: any = await batchSupplierSubmitVerify(params)
      if (res) {
        Message.success('交货成功')
        showvisible.value = false
        emits('save')
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const getSupplierName = (data: any) => {
    if (data.supplierCloseCost.semiNoPick) {
      return '供应商'
    } else {
      return data.supplierCloseCost.semiWarehouseCode == 'CK86' ? '需求方' : '采购方'
    }
  }

  onMounted(() => {
    console.log(props.info)
  })
</script>

<style lang="less" scoped>
  .img-con {
    width: 200px;
  }

  .basic-info {
    width: 200px;
    .info-con {
      margin-bottom: 5px;
      .label {
        width: 80px;
        text-align: right;
      }
    }
  }

  .setting {
    flex: 1;
  }
</style>
